package com.liang.cloud.Controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.liang.cloud.Dto.OrderDTO;
import com.liang.cloud.Emun.ResultEnum;
import com.liang.cloud.Exception.SellException;
import com.liang.cloud.Form.OrderForm;
import com.liang.cloud.Handler.SellFackHandler;
import com.liang.cloud.Util.ResultVoUtil;
import com.liang.cloud.Vo.ResultVo;
import com.liang.cloud.Converter.OrderForm2OrderDTOConverter;
import com.liang.cloud.Service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 余亮亮
 * @description:
 * @create: 2020-01-24 14:11:15
 **/
@RestController
@RequestMapping("/order/buyer")
@Slf4j
public class OrderBuyerController {

    @Autowired
    OrderService orderService;

    @PostMapping("/create")
    @SentinelResource(value = "orderBuyerCreate",fallback = "CallTimeTwoArg",fallbackClass = SellFackHandler.class)
    public ResultVo<Map<String,Object>> create(@Valid @RequestBody OrderForm orderForm,
                                               BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确, orderForm={}", orderForm);
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getList())) {
            log.error("【创建订单】购物车不能为空");
            throw new SellException(ResultEnum.CART_EMPTY);
        }
        OrderDTO orderDTO1 = orderService.create(orderDTO);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("orderId",orderDTO1.getOrderId());
        return ResultVoUtil.success(map);
    }

    @PostMapping("/load")
    public ResultVo<OrderDTO> load(@RequestBody HashMap<String,String> map){
        String openid = map.get("openid");
        if (openid.isEmpty()){
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(),"openid为null");
        }
        List<OrderDTO> orderDTOlist = orderService.findByOpenid(openid);
        return ResultVoUtil.success(orderDTOlist);
    }
}
